<?php

namespace common\components;

use yii\db\ActiveQuery as BaseActiveQuery;

/**
 * 继承原有的ActiveQuery类，扩展一些常用功能
 *
 * @package common\components
 */
class ActiveQuery extends BaseActiveQuery
{

    /**
     * @var string 标记为当前状态的字段
     */
    protected $statusColumn = 'status';

    /**
     * 判断状态码
     *
     * @param int $status
     * @return $this
     */
    public function status($status)
    {
        $this->andWhere([$this->statusColumn => (int) $status]);
        return $this;
    }

    /**
     * 主键倒序查找
     *
     * @return $this
     */
    public function desc()
    {
        /** @var ActiveRecord $model */
        $model = $this->modelClass;
        $this->orderBy([$model::primaryKey()[0] => SORT_DESC]);
        return $this;
    }

    /**
     * 主键顺序查找
     *
     * @return $this
     */
    public function asc()
    {
        /** @var ActiveRecord $model */
        $model = $this->modelClass;
        $this->orderBy([$model::primaryKey()[0] => SORT_ASC]);
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function sort()
    {
        $this->orderBy(['order_num' => SORT_DESC]);
        return $this;
    }

    /**
     * 默认根据时间来排序
     *
     * @param string $column
     * @param int    $type
     * @return $this
     */
    public function sortDate($column = 'created_at', $type = SORT_DESC)
    {
        $this->orderBy([$column => $type]);
        return $this;
    }
}
